<template>
  <div class="history-panel">
    <div class="history-header">
      <h3>出牌历史</h3>
      <div class="history-actions">
        <button class="btn btn-secondary btn-sm" @click="toggleExpanded">
          {{ isExpanded ? '收起' : '展开' }}
        </button>
      </div>
    </div>

    <div v-if="isExpanded" ref="historyContentRef" class="history-content">
      <div v-if="history.length === 0" class="empty-history">暂无出牌记录</div>

      <div v-else class="history-list">
        <div
          v-for="record in displayHistory"
          :key="record.id"
          :class="['history-item', `history-item--player-${record.playerId}`]"
          :title="getRecordTooltip(record)"
        >
          <div class="history-item-header">
            <span class="player-name">{{ record.playerName }}</span>
            <span class="round-info">R{{ record.round }}</span>
          </div>

          <div class="history-item-content">
            <div v-if="record.cards.length === 0" class="pass-action">过牌</div>
            <div v-else class="play-action">
              <div class="pattern-info">
                <span class="pattern-name">{{
                  getPatternName(record.combination.type)
                }}</span>
                <span class="pattern-power"
                  >({{ record.combination.power }})</span
                >
              </div>
              <div class="cards-display">
                <PokerCard
                  v-for="card in record.cards"
                  :key="card.id"
                  :card="card"
                  size="tiny"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 简化显示模式 -->
    <div v-else class="history-summary" @click="toggleExpanded">
      <div v-if="history.length === 0" class="summary-empty">无记录</div>
      <div v-else class="summary-stats">
        <span>共 {{ history.length }} 条记录</span>
        <span v-if="lastRecord" class="last-record">
          最后: {{ lastRecord.playerName }}
          {{
            lastRecord.cards.length === 0
              ? '过牌'
              : getPatternName(lastRecord.combination.type)
          }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { GameHistory } from '../types/game'
import { PATTERN_NAMES, Card } from '../types/card'
import PokerCard from './PokerCard.vue'
import { sortCardsByGuandanRules } from '../utils/cardUtils'

interface Props {
  history: GameHistory[]
  trumpCard: Card | null
  maxDisplayItems?: number
  autoExpand?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  maxDisplayItems: 50,
  autoExpand: false,
})

// 响应式数据
const isExpanded = ref(props.autoExpand)
const historyContentRef = ref<HTMLElement | null>(null)

// 计算属性 - 优化性能，只显示最近的记录
const displayHistory = computed(() => {
  // 按时间倒序显示（最新的在前）
  const reversed = [...props.history].reverse()
  // 限制显示数量以提升性能，并对每条记录中的牌进行排序
  return reversed.slice(0, props.maxDisplayItems).map((record) => ({
    ...record,
    cards: sortCardsByGuandanRules(record.cards, props.trumpCard),
  }))
})

const lastRecord = computed(() => {
  return props.history.length > 0
    ? props.history[props.history.length - 1]
    : null
})

// 方法
const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
}

const formatTime = (timestamp: Date): string => {
  return timestamp.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

const getPatternName = (patternType: number): string => {
  return PATTERN_NAMES[patternType as keyof typeof PATTERN_NAMES] || '未知牌型'
}

// 生成记录的悬浮提示
const getRecordTooltip = (record: GameHistory): string => {
  const time = formatTime(record.timestamp)
  const action =
    record.cards.length === 0
      ? '过牌'
      : `${getPatternName(record.combination.type)} (威力: ${record.combination.power})`
  return `${record.playerName} - ${action} - ${time}`
}

// 监听历史记录变化，自动滚动到最新记录
watch(
  () => props.history.length,
  async (newLength: number, oldLength: number) => {
    // 只在有新记录添加时才滚动
    if (newLength > oldLength && isExpanded.value && historyContentRef.value) {
      await nextTick()
      // 平滑滚动到顶部显示最新记录
      historyContentRef.value.scrollTo({
        top: 0,
        behavior: 'smooth',
      })
    }
  }
)

// 监听展开状态变化，展开时滚动到顶部
watch(isExpanded, async (expanded: boolean) => {
  if (expanded && historyContentRef.value) {
    await nextTick()
    historyContentRef.value.scrollTop = 0
  }
})
</script>

<style scoped>
.history-panel {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: var(--border-radius);
  overflow: hidden;
  transition: var(--transition);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-md);
  background: rgba(0, 0, 0, 0.2);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.history-header h3 {
  color: white;
  font-size: 14px;
  margin: 0;
}

.history-actions {
  display: flex;
  gap: var(--spacing-xs);
}

.btn-sm {
  padding: 2px 8px;
  font-size: 12px;
}

/* 历史内容 */
.history-content {
  max-height: 150px;
  overflow-y: auto;
}

.empty-history {
  padding: var(--spacing-sm);
  text-align: center;
  color: rgba(255, 255, 255, 0.6);
  font-style: italic;
  font-size: 11px;
}

.history-list {
  padding: 2px;
}

.history-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
  margin-bottom: 1px;
  padding: 2px 6px;
  border-left: 2px solid transparent;
  transition: var(--transition);
  min-height: 24px;
  display: flex;
  align-items: center;
}

/* 悬浮效果已删除 */

/* 不同玩家的颜色标识 */
.history-item--player-0 {
  border-left-color: var(--joker-color); /* AI玩家 */
}

.history-item--player-1 {
  border-left-color: var(--btn-primary); /* 玩家1 */
}

.history-item--player-2 {
  border-left-color: var(--btn-success); /* 玩家2 */
}

.history-item--player-3 {
  border-left-color: var(--suit-red); /* 玩家3 */
}

.history-item-header {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  min-width: 60px;
  flex-shrink: 0;
}

.player-name {
  color: white;
  font-weight: bold;
  font-size: 10px;
}

.round-info,
.time-info {
  color: rgba(255, 255, 255, 0.5);
  font-size: 9px;
}

.history-item-content {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
  min-width: 0;
}

.pass-action {
  color: rgba(255, 255, 255, 0.6);
  font-style: italic;
  font-size: 9px;
}

.play-action {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
  min-width: 0;
}

.pattern-info {
  display: flex;
  align-items: center;
  gap: 1px;
  font-size: 9px;
  min-width: 50px;
  flex-shrink: 0;
}

.pattern-name {
  color: white;
  font-weight: bold;
}

.pattern-power {
  color: rgba(255, 255, 255, 0.7);
  font-size: 8px;
}

.cards-display {
  display: flex;
  gap: 1px;
  flex-wrap: nowrap;
  overflow-x: auto;
  flex: 1;
  min-width: 0;
}

/* 简化显示 */
.history-summary {
  padding: var(--spacing-sm) var(--spacing-md);
  cursor: pointer;
  transition: var(--transition);
}

.history-summary:hover {
  background: rgba(255, 255, 255, 0.05);
}

.summary-empty {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  text-align: center;
}

.summary-stats {
  display: flex;
  flex-direction: column;
  gap: 2px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.8);
}

.last-record {
  color: rgba(255, 255, 255, 0.6);
  font-size: 10px;
}

/* 滚动条样式 */
.history-content::-webkit-scrollbar {
  width: 4px;
}

.history-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

.history-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}

.history-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 卡牌显示区域的水平滚动条 */
.cards-display::-webkit-scrollbar {
  height: 2px;
}

.cards-display::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
}

.cards-display::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 1px;
}

.cards-display::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-panel {
    font-size: 12px;
  }

  .history-header {
    padding: 6px 8px;
  }

  .history-header h3 {
    font-size: 11px;
  }

  .history-content {
    max-height: 120px;
  }

  .history-item {
    padding: 4px 6px;
    margin-bottom: 2px;
  }

  .history-item-header {
    min-width: 50px;
  }

  .player-name {
    font-size: 9px;
  }

  .round-info {
    font-size: 8px;
  }

  .pattern-info {
    min-width: 40px;
  }

  .pattern-name {
    font-size: 8px;
  }

  .pattern-power {
    font-size: 7px;
  }

  .pass-action {
    font-size: 8px;
  }

  .cards-display {
    gap: 0.5px;
  }

  .btn-sm {
    padding: 2px 6px;
    font-size: 10px;
  }

  .history-summary {
    padding: 6px 8px;
  }

  .summary-stats {
    font-size: 10px;
  }

  .last-record {
    font-size: 9px;
  }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .history-summary {
    padding: 8px 10px;
    -webkit-tap-highlight-color: rgba(255, 255, 255, 0.1);
  }

  .btn-sm {
    min-height: 28px;
    min-width: 44px;
    padding: 4px 8px;
  }

  .history-item {
    min-height: 32px;
  }
}
</style>
